import api from '@/api';
import wx from 'weixin-js-sdk';

export class WxShare {

  signMap = new Map();  // 存储地址url认证信息sign

  jsSDLAuthUrl = '/weixinShare/getSignature';  // 获取签名接口

  defaultShareConfig = {
    title: '教案大赛',
    desc: '分享教案描述信息',
    link: location.href,
    imgUrl: 'logo',
    jsApiList: [ 'updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ' ], // 分享给朋友分享到QQ  分享到朋友圈 分享到腾讯微博
  }

  wxShareConfig = {}


  log(val) {
    console.log('this is share', val)
    console.log('defaultShareConfig', this.defaultShareConfig)
  }

  /**
   * 
   * @param {Object} config 分页配置信息，包括title，desc，等等；
   */
  yioksShare( config = {}) {
    this.wxShareConfig.title = config.title || this.defaultShareConfig.title;
    this.wxShareConfig.desc = config.desc || this.defaultShareConfig.desc;
    this.wxShareConfig.link = config.link || this.defaultShareConfig.link;
    this.wxShareConfig.imgUrl = config.imgUrl || this.defaultShareConfig.imgUrl;
    this.wxShareConfig.jsApiList = config.jsApiList || this.defaultShareConfig;

    const signMsg = this.signMap.has(this.wxShareConfig.link)
    if(signMsg) {
      // 当前分享链接存在sign签名（是一个对象，包含appid，时间戳,nonceStr,signature等信息）
      // 注入签名信息， 并调用分享
      console.log('调用分享')
      this.injectAndShare(signMsg)

    } else {
      // 当前分享链接不存在签名 = 更新签名信息
      // 获取签名信息
      console.log('调用获取签名接口')
      this.getShareAuth(this.wxShareConfig.link)
    }
  }


  /**
   * 
   * @param {Object} signMsg 接口签名信息
   * @desc jssdk签名权限注入，并添加分享事件监听器
   */
  injectAndShare(signMsg) {

    const that = this;

    console.log('signMsg', signMsg )

    signMsg.timestamp = signMsg.timestamp.toString();
    console.log('signMsg.timestamp 转化为字符串后的结果：', signMsg)
    console.log('url 比对结果',  location.href.split('#')[0] === signMsg.url )
    wx.config({
      debug: false,  // 开发期间启用
      appId: signMsg.appId,
      timestamp: signMsg.timestamp,
      nonceStr: signMsg.noncestr,
      signature: signMsg.signature,
      jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ' ],
    })

    wx.ready(function() {
      const { title,desc,link,imgUrl } = that.wxShareConfig;
      console.log('wx.ready', '######')

      wx.checkJsApi({
        jsApiList:  ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ' ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
        success: function(res) {
        // 以键值对的形式返回，可用的api值true，不可用为false
        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          console.log('#####checkJsApi#####', res)
        }
      });

      wx.updateAppMessageShareData({
        title,desc,link,imgUrl,
        success: function() {
          console.log('分享成功！')
        },
        cancel: function() {
          console.log('分享取消！')
        },
        fail: function() {
          console.log('分享失败！')
        }
      })

       wx.updateTimelineShareData({
        title,desc,link,imgUrl,
        success: function() {
          console.log('分享成功！')
        },
        cancel: function() {
          console.log('分享取消！')
        },
        fail: function() {
          console.log('分享失败！')
        }
      })

      
       wx.onMenuShareWeibo({
        title,desc,link,imgUrl,
        success: function() {
          console.log('分享成功！')
        },
        cancel: function() {
          console.log('分享取消！')
        },
        fail: function() {
          console.log('分享失败！')
        }
      })

      // 即将废弃（为兼容安卓最好加上）
      wx.onMenuShareTimeline({
        title,desc,link,imgUrl,
        success: function() {
          console.log('分享成功！')
        },
        cancel: function() {
          console.log('分享取消！')
        },
        fail: function() {
          console.log('分享失败！')
        }
      })

      // 即将废弃（为兼容安卓最好加上）
      wx.onMenuShareAppMessage({
        title,desc,link,imgUrl,
        success: function() {
          console.log('分享成功！')
        },
        cancel: function() {
          console.log('分享取消！')
        },
        fail: function() {
          console.log('分享失败！')
        }
      })

      // 即将废弃（为兼容安卓最好加上）
      wx.onMenuShareQQ({
        title,desc,link,imgUrl,
        success: function() {
          console.log('分享成功！')
        },
        cancel: function() {
          console.log('分享取消！')
        },
        fail: function() {
          console.log('分享失败！')
        }
      })

    })

    wx.error(function(res) {
      console.log('wx error:', res)
    })

  }

  /**
   * 
   * @param {url} shareUrl 
   * @description 从服务器获取分享页面签名信息
   */
  getShareAuth(shareUrl) {
    console.log('待获取权限的地址', shareUrl)
    api({
      url: this.jsSDLAuthUrl,
      method: 'POST',
      params: {
        // requestUrl: encodeURIComponent(shareUrl)
        requestUrl: shareUrl
      }
    }).then(res => {
      // console.log('获取签名信息结果：', res)
      if(res.code) {
        console.error('res.msg', res.msg);
        return
      }
      this.signMap.set(shareUrl, res)  // 存储信息
      this.injectAndShare(res);  // 注入签名信息
    }).catch(err => {
      console.error('err', err)
    })

  }

}

